﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private Deleg del;    
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            try
            {
                conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
                conn.Open();
                DataTable dt = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_PharmSel", 30, null);
                foreach (DataRow row in dt.Rows)
                {
                    NewItem ni = new NewItem();
                    ni.ParamID = Convert.ToInt32(row[1]);
                    ni.ParamComment = row[2].ToString();
                    comboBox1.Items.Add(ni);
                }

                DataGridViewUpd();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DataGridViewUpd()
        {
            dataGridView1.DataSource = null;
            dt_rep = null;
            dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_InvestExpensesSel", 30, null);
            dataGridView1.DataSource = dt_rep.DefaultView;

            dataGridView1.Sort(dataGridView1.Columns[1],ListSortDirection.Ascending);

        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                
                dt_rep.Load(RepProc(conn));

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private SqlDataReader RepProc(SqlConnection sqlcon)//метод для вызова хранимки
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"sp_name"; //имя хранимой процедуры
            sqlcom.CommandTimeout = 300;

            

            return sqlcom.ExecuteReader();
        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "Инвестиционные расходы";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
                (new ExpToExcel()).SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.text = textBox2.Text;
            if (f2.ShowDialog() == DialogResult.OK)
                textBox2.Text = f2.text;
            f2.Close();
            f2 = null;
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            HideShowRows();
        }

        private void textBox3_Enter(object sender, EventArgs e)
        {
            HideShowRows();
        }

        private void HideShowRows()
        {
            try
            {
                CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
                cm.SuspendBinding();
                foreach (DataGridViewRow r in dataGridView1.Rows)
                {
                    r.Visible = true;
                    if (!Regex.Match(Convert.ToString(dataGridView1[dataGridView1.SortedColumn.Name, r.Index].Value), textBox3.Text, RegexOptions.IgnoreCase).Success)
                        r.Visible = false;
                }
                cm.ResumeBinding();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.') e.KeyChar = ',';
            if (!(Char.IsDigit(e.KeyChar)) && !((e.KeyChar == ',') && (textBox1.Text.IndexOf(",") == -1) && (textBox1.Text.Length != 0)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex > -1 && e.RowIndex > -1)
                {
                    for (int i = 0; i < comboBox1.Items.Count; i++)
                    {
                        if (Convert.ToInt32((comboBox1.Items[i] as NewItem).ParamID) == Convert.ToInt32(dataGridView1[0, e.RowIndex].Value))
                        {
                            comboBox1.SelectedIndex = i;
                            break;
                        }
                    }

                    if (dataGridView1[4, e.RowIndex].Value == DBNull.Value) textBox2.Text = "";
                    textBox2.Text = dataGridView1[4, e.RowIndex].Value.ToString();

                    textBox1.Text = dataGridView1[3, e.RowIndex].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.Text == "")
                {
                    MessageBox.Show("Выберите аптеку");
                    comboBox1.Focus();
                }
                else
                {
                    if (textBox1.Text == "")
                    {
                        MessageBox.Show("Введите сумму");
                        textBox1.Focus();
                    }
                    else
                    {
                        SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[3];
                        par[0].name = "@pharmcode";
                        par[0].value = Convert.ToInt32((comboBox1.SelectedItem as NewItem).ParamID);
                        par[1].name = "@invsum";
                        par[1].value = textBox1.Text.Replace(',','.');
                        par[2].name = "@comm";
                        par[2].value = textBox2.Text;

                        (new SqlStorProc()).SqlProcExecNonQuery(conn, "pas_InvestExpensesInsUpd", 30, par);

                        DataGridViewUpd();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}
